//
//  PermissionManager.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/7/11.
//

import Foundation
import AVFoundation
import Photos
import CoreLocation
//import UserNotifications
//import Contacts
//import EventKit
//import Speech
//import CoreBluetooth
//import HealthKit
//import MediaPlayer
//import Intents
//import CoreMotion
//import AppTrackingTransparency

// MARK: - 权限类型枚举
/// 定义应用中可能需要的所有权限类型
enum PermissionType: Hashable {
    case camera
    case microphone
    case photoLibrary
    case locationWhenInUse
    case locationAlways
//    case notifications(options: UNAuthorizationOptions)
//    case contacts
//    case calendar
//    case reminders
//    case speechRecognition
//    case bluetooth
//    case health(typesToShareIdentifiers: [String]?, typesToReadIdentifiers: [String]?)
//    case mediaLibrary
//    case siri
//    case motion
//    case trackingAuthorization
    
    /// 获取权限的描述名称
    var description: String {
        switch self {
        case .camera: return "Camera"
        case .microphone: return "Microphone"
        case .photoLibrary: return "Photo Library"
        case .locationWhenInUse, .locationAlways: return "Location"
//        case .notifications: return "Notifications"
//        case .contacts: return "Contacts"
//        case .calendar: return "Calendar"
//        case .reminders: return "Reminders"
//        case .speechRecognition: return "Speech Recognition"
//        case .bluetooth: return "Bluetooth"
//        case .health: return "Health Data"
//        case .mediaLibrary: return "Media Library"
//        case .siri: return "Siri"
//        case .motion: return "Motion & Fitness"
//        case .trackingAuthorization: return "App Tracking"
        }
    }
    
    var descriptionZH: String {
        switch self {
        case .camera: return "相机"
        case .microphone: return "麦克风"
        case .photoLibrary: return "相册"
        case .locationWhenInUse, .locationAlways: return "位置"
//        case .notifications: return "通知"
//        case .contacts: return "通讯录"
//        case .calendar: return "日历"
//        case .reminders: return "提醒事项"
//        case .speechRecognition: return "语音识别"
//        case .bluetooth: return "蓝牙"
//        case .health: return "健康数据"
//        case .mediaLibrary: return "媒体库"
//        case .siri: return "Siri"
//        case .motion: return "运动与健身"
//        case .trackingAuthorization: return "跟踪"
        }
    }
    
    
    // 实现 hash(into:) 方法以确保正确哈希
    func hash(into hasher: inout Hasher) {
        switch self {
        case .camera:
            hasher.combine(0)
        case .microphone:
            hasher.combine(1)
        case .photoLibrary:
            hasher.combine(2)
        case .locationWhenInUse:
            hasher.combine(3)
        case .locationAlways:
            hasher.combine(4)
//        case .notifications(let options):
//            hasher.combine(5)
//            hasher.combine(options.rawValue)
//        case .contacts:
//            hasher.combine(6)
//        case .calendar:
//            hasher.combine(7)
//        case .reminders:
//            hasher.combine(8)
//        case .speechRecognition:
//            hasher.combine(9)
//        case .bluetooth:
//            hasher.combine(10)
//        case .health(let typesToShareIdentifiers, let typesToReadIdentifiers):
//            hasher.combine(11)
//            hasher.combine(typesToShareIdentifiers)
//            hasher.combine(typesToReadIdentifiers)
//        case .mediaLibrary:
//            hasher.combine(12)
//        case .siri:
//            hasher.combine(13)
//        case .motion:
//            hasher.combine(14)
//        case .trackingAuthorization:
//            hasher.combine(15)
        }
    }
    
    // 实现 == 运算符以确保正确比较
    static func == (lhs: PermissionType, rhs: PermissionType) -> Bool {
        switch (lhs, rhs) {
        case (.camera, .camera): return true
        case (.microphone, .microphone): return true
        case (.photoLibrary, .photoLibrary): return true
        case (.locationWhenInUse, .locationWhenInUse): return true
        case (.locationAlways, .locationAlways): return true
//        case (.notifications(let lhsOptions), .notifications(let rhsOptions)):
//            return lhsOptions == rhsOptions
//        case (.contacts, .contacts): return true
//        case (.calendar, .calendar): return true
//        case (.reminders, .reminders): return true
//        case (.speechRecognition, .speechRecognition): return true
//        case (.bluetooth, .bluetooth): return true
//        case (.health(let lhsShare, let lhsRead), .health(let rhsShare, let rhsRead)):
//            return lhsShare == rhsShare && lhsRead == rhsRead
//        case (.mediaLibrary, .mediaLibrary): return true
//        case (.siri, .siri): return true
//        case (.motion, .motion): return true
//        case (.trackingAuthorization, .trackingAuthorization): return true
        default: return false
        }
    }
}

// MARK: - 权限状态枚举
/// 定义权限可能的各种状态
enum PermissionStatus: CustomStringConvertible {
    case authorized
    case denied
    case notDetermined
    case restricted
    case unknown
    case limited
    
    /// 状态描述
    var description: String {
        switch self {
        case .authorized: return "已授权"
        case .denied: return "用户已拒绝"
        case .notDetermined: return "还未请求权限"
        case .restricted: return "受限制的"
        case .limited: return "Limited"
        case .unknown: return "Unknown"
        }
    }
}

// MARK: - 权限管理器主类
/// 统一管理所有系统权限请求的类
final class PermissionManager: NSObject {
    
    // 单例模式
    static let shared = PermissionManager()
    private override init() {}
    
    // 位置权限相关属性
    private var locationManager: CLLocationManager?
    private var locationCompletion: ((PermissionStatus) -> Void)?
    
    // 运动权限相关属性
//    private var motionActivityManager: CMMotionActivityManager?
    
    // MARK: - 公开方法
    
    /// 请求指定类型的权限
    /// - Parameters:
    ///   - permission: 权限类型
    ///   - completion: 完成回调，返回权限状态
    func requestPermission(_ permission: PermissionType, completion: @escaping (PermissionStatus) -> Void) {
        DispatchQueue.main.async {
            switch permission {
            case .camera:
                self.requestCameraPermission(completion: completion)
            case .microphone:
                self.requestMicrophonePermission(completion: completion)
            case .photoLibrary:
                self.requestPhotoLibraryPermission(completion: completion)
            case .locationWhenInUse:
                self.requestLocationPermission(always: false, completion: completion)
            case .locationAlways:
                self.requestLocationPermission(always: true, completion: completion)
//            case .notifications(let options):
//                self.requestNotificationPermission(options: options, completion: completion)
//            case .contacts:
//                self.requestContactsPermission(completion: completion)
//            case .calendar:
//                self.requestCalendarPermission(completion: completion)
//            case .reminders:
//                self.requestRemindersPermission(completion: completion)
//            case .speechRecognition:
//                self.requestSpeechRecognitionPermission(completion: completion)
//            case .bluetooth:
//                self.requestBluetoothPermission(completion: completion)
//            case .health(let typesToShareIdentifiers, let typesToReadIdentifiers):
//                self.requestHealthPermission(
//                    typesToShareIdentifiers: typesToShareIdentifiers,
//                    typesToReadIdentifiers: typesToReadIdentifiers,
//                    completion: completion
//                )
//            case .mediaLibrary:
//                self.requestMediaLibraryPermission(completion: completion)
//            case .siri:
//                self.requestSiriPermission(completion: completion)
//            case .motion:
//                self.requestMotionPermission(completion: completion)
//            case .trackingAuthorization:
//                self.requestTrackingAuthorizationPermission(completion: completion)
            }
        }
    }
    
    /// 检查指定权限的当前状态
    /// - Parameters:
    ///   - permission: 权限类型
    ///   - completion: 完成回调，返回权限状态
    func checkPermissionStatus(_ permission: PermissionType, completion: @escaping (PermissionStatus) -> Void) {
        DispatchQueue.main.async {
            switch permission {
            case .camera:
                self.checkCameraPermissionStatus(completion: completion)
            case .microphone:
                self.checkMicrophonePermissionStatus(completion: completion)
            case .photoLibrary:
                self.checkPhotoLibraryPermissionStatus(completion: completion)
            case .locationWhenInUse:
                self.checkLocationPermissionStatus(always: false, completion: completion)
            case .locationAlways:
                self.checkLocationPermissionStatus(always: true, completion: completion)
//            case .notifications:
//                self.checkNotificationPermissionStatus(completion: completion)
//            case .contacts:
//                self.checkContactsPermissionStatus(completion: completion)
//            case .calendar:
//                self.checkCalendarPermissionStatus(completion: completion)
//            case .reminders:
//                self.checkRemindersPermissionStatus(completion: completion)
//            case .speechRecognition:
//                self.checkSpeechRecognitionPermissionStatus(completion: completion)
//            case .bluetooth:
//                self.checkBluetoothPermissionStatus(completion: completion)
//            case .health(let typesToShareIdentifiers, let typesToReadIdentifiers):
//                self.checkHealthPermissionStatus(
//                    typesToShareIdentifiers: typesToShareIdentifiers,
//                    typesToReadIdentifiers: typesToReadIdentifiers,
//                    completion: completion
//                )
//            case .mediaLibrary:
//                self.checkMediaLibraryPermissionStatus(completion: completion)
//            case .siri:
//                self.checkSiriPermissionStatus(completion: completion)
//            case .motion:
//                self.checkMotionPermissionStatus(completion: completion)
//            case .trackingAuthorization:
//                self.checkTrackingAuthorizationStatus(completion: completion)
            }
        }
    }
    
    /// 批量请求多个权限
    /// - Parameters:
    ///   - permissions: 权限类型数组
    ///   - completion: 完成回调，返回权限类型和状态的字典
    func requestMultiplePermissions(_ permissions: [PermissionType], completion: @escaping ([PermissionType: PermissionStatus]) -> Void) {
        var results = [PermissionType: PermissionStatus]()
        let group = DispatchGroup()
        
        for permission in permissions {
            group.enter()
            requestPermission(permission) { status in
                results[permission] = status
                group.leave()
            }
        }
        
        group.notify(queue: .main) {
            completion(results)
        }
    }
    
    /// 打开应用设置页面（引导用户手动修改权限）
    func openAppSettings() {
        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString),
              UIApplication.shared.canOpenURL(settingsUrl) else {
            return
        }
        
        UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
    }
    
    // MARK: - 具体权限实现
    
    // MARK: 相机权限
    private func requestCameraPermission(completion: @escaping (PermissionStatus) -> Void) {
        AVCaptureDevice.requestAccess(for: .video) { granted in
            DispatchQueue.main.async {
                completion(granted ? .authorized : .denied)
            }
        }
    }
    
    private func checkCameraPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        completion(mapAVAuthorizationStatus(status))
    }
    
    // MARK: 麦克风权限
    private func requestMicrophonePermission(completion: @escaping (PermissionStatus) -> Void) {
        AVAudioSession.sharedInstance().requestRecordPermission { granted in
            DispatchQueue.main.async {
                completion(granted ? .authorized : .denied)
            }
        }
    }
    
    private func checkMicrophonePermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
        let status = AVCaptureDevice.authorizationStatus(for: .audio)
        completion(mapAVAuthorizationStatus(status))
    }
    
    // MARK: 照片库权限
    private func requestPhotoLibraryPermission(completion: @escaping (PermissionStatus) -> Void) {
        if #available(iOS 14, *) {
            PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in
                DispatchQueue.main.async {
                    completion(self.mapPHAuthorizationStatus(status))
                }
            }
        } else {
            PHPhotoLibrary.requestAuthorization { status in
                DispatchQueue.main.async {
                    completion(self.mapPHAuthorizationStatus(status))
                }
            }
        }
    }
    
    private func checkPhotoLibraryPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
        let status: PHAuthorizationStatus
        if #available(iOS 14, *) {
            status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
        } else {
            status = PHPhotoLibrary.authorizationStatus()
        }
        completion(mapPHAuthorizationStatus(status))
    }
    
    // MARK: 位置权限
    private func requestLocationPermission(always: Bool, completion: @escaping (PermissionStatus) -> Void) {
        guard CLLocationManager.locationServicesEnabled() else {
            completion(.denied)
            return
        }
        
        locationCompletion = completion
        locationManager = CLLocationManager()
        locationManager?.delegate = self
        
        if always {
            locationManager?.requestAlwaysAuthorization()
        } else {
            locationManager?.requestWhenInUseAuthorization()
        }
    }
    
    private func checkLocationPermissionStatus(always: Bool, completion: @escaping (PermissionStatus) -> Void) {
        guard CLLocationManager.locationServicesEnabled() else {
            completion(.denied)
            return
        }
        
        let status: CLAuthorizationStatus
        if #available(iOS 14.0, *) {
            status = locationManager?.authorizationStatus ?? .notDetermined
        } else {
            status = CLLocationManager.authorizationStatus()
        }
        completion(mapCLAuthorizationStatus(status, always: always))
    }
    
//    // MARK: 通知权限
//    private func requestNotificationPermission(options: UNAuthorizationOptions, completion: @escaping (PermissionStatus) -> Void) {
//        UNUserNotificationCenter.current().requestAuthorization(options: options) { granted, _ in
//            DispatchQueue.main.async {
//                completion(granted ? .authorized : .denied)
//            }
//        }
//    }
//    
//    private func checkNotificationPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
//        UNUserNotificationCenter.current().getNotificationSettings { settings in
//            DispatchQueue.main.async {
//                switch settings.authorizationStatus {
//                case .authorized, .provisional, .ephemeral:
//                    completion(.authorized)
//                case .denied:
//                    completion(.denied)
//                case .notDetermined:
//                    completion(.notDetermined)
//                @unknown default:
//                    completion(.unknown)
//                }
//            }
//        }
//    }
//    
//    // MARK: 通讯录权限
//    private func requestContactsPermission(completion: @escaping (PermissionStatus) -> Void) {
//        let store = CNContactStore()
//        store.requestAccess(for: .contacts) { granted, error in
//            DispatchQueue.main.async {
//                if granted {
//                    completion(.authorized)
//                } else {
//                    completion(error == nil ? .denied : .unknown)
//                }
//            }
//        }
//    }
//    
//    private func checkContactsPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
//        let status = CNContactStore.authorizationStatus(for: .contacts)
//        switch status {
//        case .authorized: completion(.authorized)
//        case .denied: completion(.denied)
//        case .restricted: completion(.restricted)
//        case .notDetermined: completion(.notDetermined)
//        case .limited: completion(.limited)
//        @unknown default: completion(.unknown)
//        }
//    }
//    
//    // MARK: 日历权限
//    private func requestCalendarPermission(completion: @escaping (PermissionStatus) -> Void) {
//        let store = EKEventStore()
//        store.requestAccess(to: .event) { granted, error in
//            DispatchQueue.main.async {
//                if granted {
//                    completion(.authorized)
//                } else {
//                    completion(error == nil ? .denied : .unknown)
//                }
//            }
//        }
//    }
//    
//    private func checkCalendarPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
//        let status = EKEventStore.authorizationStatus(for: .event)
//        completion(mapEKAuthorizationStatus(status))
//    }
//    
//    // MARK: 提醒事项权限
//    private func requestRemindersPermission(completion: @escaping (PermissionStatus) -> Void) {
//        let store = EKEventStore()
//        store.requestAccess(to: .reminder) { granted, error in
//            DispatchQueue.main.async {
//                if granted {
//                    completion(.authorized)
//                } else {
//                    completion(error == nil ? .denied : .unknown)
//                }
//            }
//        }
//    }
//    
//    private func checkRemindersPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
//        let status = EKEventStore.authorizationStatus(for: .reminder)
//        completion(mapEKAuthorizationStatus(status))
//    }
//    
//    // MARK: 语音识别权限
//    private func requestSpeechRecognitionPermission(completion: @escaping (PermissionStatus) -> Void) {
//        SFSpeechRecognizer.requestAuthorization { status in
//            DispatchQueue.main.async {
//                switch status {
//                case .authorized: completion(.authorized)
//                case .denied: completion(.denied)
//                case .restricted: completion(.restricted)
//                case .notDetermined: completion(.notDetermined)
//                @unknown default: completion(.unknown)
//                }
//            }
//        }
//    }
//    
//    private func checkSpeechRecognitionPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
//        let status = SFSpeechRecognizer.authorizationStatus()
//        switch status {
//        case .authorized: completion(.authorized)
//        case .denied: completion(.denied)
//        case .restricted: completion(.restricted)
//        case .notDetermined: completion(.notDetermined)
//        @unknown default: completion(.unknown)
//        }
//    }
//    
//    // MARK: 蓝牙权限
//    private func requestBluetoothPermission(completion: @escaping (PermissionStatus) -> Void) {
//        if #available(iOS 13.0, *) {
//            let status = CBManager.authorization
//            completion(mapCBManagerAuthorizationStatus(status))
//        } else {
//            completion(.authorized)
//        }
//    }
//    
//    private func checkBluetoothPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
//        if #available(iOS 13.0, *) {
//            let status = CBManager.authorization
//            completion(mapCBManagerAuthorizationStatus(status))
//        } else {
//            completion(.authorized)
//        }
//    }
//    
//    // MARK: 健康数据权限
//    private func requestHealthPermission(typesToShareIdentifiers: [String]?, typesToReadIdentifiers: [String]?, completion: @escaping (PermissionStatus) -> Void) {
//        guard HKHealthStore.isHealthDataAvailable() else {
//            completion(.notDetermined)
//            return
//        }
//        
//        let healthStore = HKHealthStore()
//        
//        // 将标识符转换为对应的类型
//        let typesToShare = typesToShareIdentifiers?.compactMap { identifier in
//            HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: identifier)) ??
//            HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier(rawValue: identifier))
//        }
//        
//        let typesToRead = typesToReadIdentifiers?.compactMap { identifier in
//            HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: identifier)) ??
//            HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier(rawValue: identifier))
//        }
//        
//        healthStore.requestAuthorization(toShare: Set(typesToShare ?? []),
//                                         read: Set(typesToRead ?? [])) { success, error in
//            DispatchQueue.main.async {
//                if success {
//                    completion(.authorized)
//                } else {
//                    completion(error == nil ? .denied : .unknown)
//                }
//            }
//        }
//    }
//    
//    private func checkHealthPermissionStatus(typesToShareIdentifiers: [String]?,
//                                             typesToReadIdentifiers: [String]?,
//                                             completion: @escaping (PermissionStatus) -> Void) {
//        guard HKHealthStore.isHealthDataAvailable() else {
//            completion(.notDetermined)
//            return
//        }
//        
//        // 健康权限需要检查具体类型的授权状态
//        // 这里简化处理，实际使用时可能需要更详细的检查
//        completion(.unknown)
//    }
//    
//    // MARK: 媒体库权限
//    private func requestMediaLibraryPermission(completion: @escaping (PermissionStatus) -> Void) {
//        MPMediaLibrary.requestAuthorization { status in
//            DispatchQueue.main.async {
//                switch status {
//                case .authorized: completion(.authorized)
//                case .denied: completion(.denied)
//                case .restricted: completion(.restricted)
//                case .notDetermined: completion(.notDetermined)
//                @unknown default: completion(.unknown)
//                }
//            }
//        }
//    }
//    
//    private func checkMediaLibraryPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
//        let status = MPMediaLibrary.authorizationStatus()
//        switch status {
//        case .authorized: completion(.authorized)
//        case .denied: completion(.denied)
//        case .restricted: completion(.restricted)
//        case .notDetermined: completion(.notDetermined)
//        @unknown default: completion(.unknown)
//        }
//    }
//    
//    // MARK: Siri权限
//    private func requestSiriPermission(completion: @escaping (PermissionStatus) -> Void) {
//        INPreferences.requestSiriAuthorization { status in
//            DispatchQueue.main.async {
//                switch status {
//                case .authorized: completion(.authorized)
//                case .denied: completion(.denied)
//                case .restricted: completion(.restricted)
//                case .notDetermined: completion(.notDetermined)
//                @unknown default: completion(.unknown)
//                }
//            }
//        }
//    }
//    
//    private func checkSiriPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
//        let status = INPreferences.siriAuthorizationStatus()
//        switch status {
//        case .authorized: completion(.authorized)
//        case .denied: completion(.denied)
//        case .restricted: completion(.restricted)
//        case .notDetermined: completion(.notDetermined)
//        @unknown default: completion(.unknown)
//        }
//    }
//    
//    // MARK: 运动与健身权限
//    private func requestMotionPermission(completion: @escaping (PermissionStatus) -> Void) {
//        guard CMMotionActivityManager.isActivityAvailable() else {
//            completion(.notDetermined)
//            return
//        }
//        
//        motionActivityManager = CMMotionActivityManager()
//        let today = Date()
//        
//        motionActivityManager?.queryActivityStarting(from: today, to: today, to: .main) { _, error in
//            DispatchQueue.main.async {
//                if let error = error {
//                    // 处理错误
//                    if (error as NSError).code == Int(CMErrorMotionActivityNotAuthorized.rawValue) {
//                        completion(.denied)
//                    } else if (error as NSError).code == Int(CMErrorMotionActivityNotAvailable.rawValue) {
//                        completion(.restricted)
//                    } else {
//                        completion(.unknown)
//                    }
//                } else {
//                    // 没有错误表示已授权
//                    completion(.authorized)
//                }
//                
//                // 清理
//                self.motionActivityManager = nil
//            }
//        }
//    }
//    
//    private func checkMotionPermissionStatus(completion: @escaping (PermissionStatus) -> Void) {
//        if CMMotionActivityManager.isActivityAvailable() {
//            completion(.authorized)
//        } else {
//            completion(.denied)
//        }
//    }
//    
//    // MARK: 广告追踪权限 (App Tracking Transparency)
//    private func requestTrackingAuthorizationPermission(completion: @escaping (PermissionStatus) -> Void) {
//        if #available(iOS 14, *) {
//            ATTrackingManager.requestTrackingAuthorization { status in
//                DispatchQueue.main.async {
//                    switch status {
//                    case .authorized: completion(.authorized)
//                    case .denied: completion(.denied)
//                    case .restricted: completion(.restricted)
//                    case .notDetermined: completion(.notDetermined)
//                    @unknown default: completion(.unknown)
//                    }
//                }
//            }
//        } else {
//            completion(.authorized)
//        }
//    }
//    
//    private func checkTrackingAuthorizationStatus(completion: @escaping (PermissionStatus) -> Void) {
//        if #available(iOS 14, *) {
//            let status = ATTrackingManager.trackingAuthorizationStatus
//            switch status {
//            case .authorized: completion(.authorized)
//            case .denied: completion(.denied)
//            case .restricted: completion(.restricted)
//            case .notDetermined: completion(.notDetermined)
//            @unknown default: completion(.unknown)
//            }
//        } else {
//            completion(.authorized)
//        }
//    }
    
    // MARK: - 状态映射方法
    
    private func mapAVAuthorizationStatus(_ status: AVAuthorizationStatus) -> PermissionStatus {
        switch status {
        case .authorized: return .authorized
        case .denied: return .denied
        case .notDetermined: return .notDetermined
        case .restricted: return .restricted
        @unknown default: return .unknown
        }
    }
    
    private func mapPHAuthorizationStatus(_ status: PHAuthorizationStatus) -> PermissionStatus {
        switch status {
        case .authorized: return .authorized
        case .denied: return .denied
        case .notDetermined: return .notDetermined
        case .restricted: return .restricted
        case .limited: return .limited
        @unknown default: return .unknown
        }
    }
    
    private func mapCLAuthorizationStatus(_ status: CLAuthorizationStatus, always: Bool) -> PermissionStatus {
        switch status {
        case .authorizedAlways:
            return .authorized
        case .authorizedWhenInUse:
            return always ? .denied : .authorized
        case .denied:
            return .denied
        case .notDetermined:
            return .notDetermined
        case .restricted:
            return .restricted
        @unknown default:
            return .unknown
        }
    }
    
//    private func mapEKAuthorizationStatus(_ status: EKAuthorizationStatus) -> PermissionStatus {
//        switch status {
//        case .authorized: return .authorized
//        case .denied: return .denied
//        case .notDetermined: return .notDetermined
//        case .restricted: return .restricted
//        default: return .unknown
//        }
//    }
//    
//    @available(iOS 13.0, *)
//    private func mapCBManagerAuthorizationStatus(_ status: CBManagerAuthorization) -> PermissionStatus {
//        switch status {
//        case .allowedAlways: return .authorized
//        case .denied: return .denied
//        case .restricted: return .restricted
//        case .notDetermined: return .notDetermined
//        @unknown default: return .unknown
//        }
//    }
}

// MARK: - CLLocationManagerDelegate 扩展
extension PermissionManager: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        guard let completion = locationCompletion else { return }
        
        let permissionStatus = mapCLAuthorizationStatus(status, always: false)
        completion(permissionStatus)
        
        // 清理
        locationCompletion = nil
        locationManager = nil
    }
    
    @available(iOS 14.0, *)
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        guard let completion = locationCompletion else { return }
        
        let status = manager.authorizationStatus
        let permissionStatus = mapCLAuthorizationStatus(status, always: false)
        completion(permissionStatus)
        
        // 清理
        locationCompletion = nil
        locationManager = nil
    }
}

extension PermissionManager {
    func alert(controller: UIViewController, type: PermissionType) {
        let message = "请打开系统设置中\"隐私->\(type.description)\"，允许\"\(Bundle.sg.appDisplayName)\"访问您的\(type.description)。"
        let alerController = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        alerController.addAction(UIAlertAction(title: "取消", style: .cancel) { _ in })
        alerController.addAction(UIAlertAction(title: "设置", style: .default) { action in
            PermissionManager.shared.openAppSettings()
        })
        controller.present(alerController)
    }
}
